import datetime
import re
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait

from compements.tool import process_date


def check_sf_date(driver, skip, record):
    if skip is False:
        sf_sj = []

        print("随访日期读表")
        new_sf_time = process_date(record['随访日期'])
        new_year = new_sf_time.split('-')[0]
        print("需要新建随访的年份", new_year)

        driver.switch_to.default_content()

        WebDriverWait(driver, 10).until(
            ec.presence_of_element_located((By.XPATH, "//dt[contains(text(),'随访服务')]"))).click()
        time.sleep(1)
        try:
            WebDriverWait(driver, 10).until(
                ec.presence_of_element_located((By.XPATH, "//li[contains(text(),'慢病随访')]"))).click()
        except:
            WebDriverWait(driver, 10).until(
                ec.presence_of_element_located((By.XPATH, "//dt[contains(text(),'随访服务')]"))).click()
            time.sleep(1)
            WebDriverWait(driver, 10).until(
                ec.presence_of_element_located((By.XPATH, "//li[contains(text(),'慢病随访')]"))).click()
        time.sleep(1)

        # 切换到第一个 iframe
        first_iframe = WebDriverWait(driver, 10).until(
            ec.presence_of_element_located((By.XPATH, '//*[@id="ext-gen21"]/iframe')))
        driver.switch_to.frame(first_iframe)

        try:
            # 找到包含 "2024" 的所有年份元素
            year_cells = WebDriverWait(driver, 5).until(ec.presence_of_all_elements_located(
                (By.XPATH, f'//td/div[text()="{new_year}"]')))
        except:
            return sf_sj

        year_element = WebDriverWait(driver, 5).until(ec.presence_of_element_located(
            (By.XPATH, f'//*[@id="ext-gen14-gp-year-{new_year}"]')))
        year_class = year_element.get_attribute('class')
        if year_class == 'x-grid-group':
            print("年份已展开")
        else:
            print("年份未展开，正在展开...")
            year_element.click()
            time.sleep(1)

        # 获取已有随访的日期

        try:
            elements = WebDriverWait(driver, 15).until(ec.presence_of_all_elements_located((By.XPATH,
                                                                                            f"//div[@id='ext-gen14-gp-year-{new_year}-bd']//div[@class='x-grid3-cell-inner x-grid3-col-1 x-unselectable']")))
            for element in elements:
                year = new_year
                month_and_day = element.text.split("-")
                day = int(month_and_day[1].split('(')[0])
                month = int(month_and_day[0])
                # 构造日期
                date_string = "{}-{}-{}".format(year, month, day)
                sf_sj.append(date_string)
        except Exception as e:
            print(f"{new_year}暂无随访记录")

    else:
        # 获取当前日期
        current_year = datetime.datetime.now().year
        current_year = str(current_year)

        driver.switch_to.default_content()

        WebDriverWait(driver, 10).until(
            ec.presence_of_element_located((By.XPATH, "//dt[contains(text(),'随访服务')]"))).click()
        time.sleep(1)
        try:
            WebDriverWait(driver, 10).until(
                ec.presence_of_element_located((By.XPATH, "//li[contains(text(),'慢病随访')]"))).click()
        except:
            WebDriverWait(driver, 10).until(
                ec.presence_of_element_located((By.XPATH, "//dt[contains(text(),'随访服务')]"))).click()
            time.sleep(1)
            WebDriverWait(driver, 10).until(
                ec.presence_of_element_located((By.XPATH, "//li[contains(text(),'慢病随访')]"))).click()
        time.sleep(1)

        # 切换到第一个 iframe
        first_iframe = WebDriverWait(driver, 10).until(
            ec.presence_of_element_located((By.XPATH, '//*[@id="ext-gen21"]/iframe')))
        driver.switch_to.frame(first_iframe)

        # 获取已有随访的日期
        sf_sj = []
        try:
            elements = WebDriverWait(driver, 15).until(ec.presence_of_all_elements_located((By.XPATH,
                                                                                            f"//div[@id='ext-gen14-gp-year-{current_year}-bd']//div[@class='x-grid3-cell-inner x-grid3-col-1 x-unselectable']")))
            for element in elements:
                year = current_year
                month_and_day = element.text.split("-")
                day = int(month_and_day[1].split('(')[0])
                month = int(month_and_day[0])
                # 构造日期
                date_string = "{}-{}-{}".format(year, month, day)
                sf_sj.append(date_string)
        except Exception as e:
            print(f"{current_year}暂无随访记录")

    return sf_sj
